package com.wjw.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjw.pojo.Book;
import com.wjw.pojo.Order;
import com.wjw.pojo.Reader;
import com.wjw.service.BookService;
import com.wjw.service.OrderService;
import com.wjw.service.ReaderService;
import com.wjw.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("order")
public class OrderController {

    @Autowired
    private BookService bookService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ReaderService readerService;


    //查询所有订单(管理员的)
    @RequestMapping("/listOrder")
    public String list(@RequestParam(required = false,value = "pageNum",defaultValue = "1")Integer pageNum,
                       @RequestParam(required = false,value = "pageSize",defaultValue = "10")Integer pageSize, Model model,
                       Order order){
        if (pageNum<=0||pageNum.equals("")||pageNum==null){
            pageNum=1;
        }
        if (pageSize<=0||pageSize.equals("")||pageSize==null){
            pageSize=10;
        }
        Integer id = order.getId();
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<Order> list = orderService.listOrder(id);
        model.addAttribute("pageInfo",list);
        return "order-list";
    }

    //删除订单(管理员的)
    @RequestMapping("delOrder/{id}")
    public String delReaderBook(@PathVariable("id") Integer id){
        boolean b = orderService.removeById(id);
        return "redirect:/order/listOrder";
    }

    //批量删除(管理员的)
    @PostMapping("batchDeleteOrder")
    @ResponseBody
    public String batchDeleteOrder(String idList){
        String[]split= StrUtil.split(idList,",");
        List<Integer> list=new ArrayList<>();

        for (String s : split) {
            if (!s.isEmpty()){
                int i = Integer.parseInt(s);
                list.add(i);
            }
        }
        boolean b = orderService.removeByIds(list);
        if (b){
            return "OK";
        }else {
            return "error";
        }
    }


    @RequestMapping("myOrders")
    public String myOrders(@RequestParam(required = false,defaultValue = "1",value = "pageNum") Integer pageNum,
                           @RequestParam(required = false,defaultValue = "10",value = "pageSize") Integer pageSize, Model model, Book book, HttpSession session){


        if (pageNum <= 0 || pageNum.equals("") || pageNum == null) {
            pageNum = 1;
        }
        if (pageSize <= 0 || pageSize.equals("") || pageSize == null) {
            pageSize = 10;
        }
        Integer userId =(Integer) session.getAttribute("userId");
        PageHelper.startPage(pageNum, pageSize);
        String bookName = book.getBname();
        PageInfo<Order> pageInfo=orderService.listMyOrders(userId,bookName);
        model.addAttribute("pageInfo",pageInfo);
        return "myOrders-list";
    }

    //购物车
    @RequestMapping("cart")
    public String cart(Model model,HttpSession session){
        Integer userId =(Integer) session.getAttribute("userId");
        PageInfo<Order>pageInfo=orderService.myCart(userId);
        Integer a=0;
        List<Order> list = pageInfo.getList();
        for (Order order : list) {
            a+=order.getTotal();
        }
        model.addAttribute("totalMoney",a);
        model.addAttribute("pageInfo",pageInfo);
        return "cart";
    }

    //修改订单
    @RequestMapping("updateOrder")
    @ResponseBody
    public String updateOrder(Integer orderId,Integer count){
        Order order = orderService.getById(orderId);
        Integer oldCount = order.getCount();
        Integer bid = order.getBid();
        Book book = bookService.getById(bid);
        Integer price = book.getPrice();
        order.setId(orderId);
        order.setCount(count);
        order.setTotal(count*price);
        boolean b = orderService.updateById(order);
        //修改库存
        if (oldCount>count){
            book.setStock(book.getStock()+(oldCount-count));
            bookService.updateById(book);
        }else {
            book.setStock(book.getStock()-(count-oldCount));
            bookService.updateById(book);
        }
        if (b){
            return "OK";
        }else {
            return "error";
        }
    }


    //读者添加到购物车
    @RequestMapping("bookToCart/{bookId}")
    public String foodToCart(@PathVariable Integer bookId, HttpSession session){

        Integer userId =(Integer) session.getAttribute("userId");
        QueryWrapper<Order> qw=new QueryWrapper<>();
        qw.eq("rid",userId);
        qw.eq("bid",bookId);
        qw.eq("isorder",0);
        Order one = orderService.getOne(qw);
        if (one!=null){
            session.setAttribute("msg","此书籍已加入购物车");
            return "redirect:/book/listBook";
        }
        Book book = bookService.getById(bookId);
        Order order = new Order();
        order.setBid(bookId);
        order.setRid(userId);
        order.setCount(1);
        order.setTotal(book.getPrice());
        orderService.save(order);
        session.removeAttribute("msg");
        return "redirect:/order/cart";
    }

    //删除购物车
    @RequestMapping("delCart/{orderId}")
    public String delCart(@PathVariable Integer orderId,HttpSession session){
        boolean remove = orderService.removeById(orderId);
        session.removeAttribute("msg");
        return "redirect:/order/cart";
    }


    //支付购物车
    @RequestMapping("payOrder")
    public String payOrder(HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        QueryWrapper<Order>qw=new QueryWrapper<>();
        qw.eq("rid",userId);
        qw.eq("isorder",0);
        List<Order> list = orderService.list(qw);
        int a=0;
        for (Order order : list) {
            a+=order.getTotal();
        }
        if (a>readerService.getById(userId).getMoney()){
            session.setAttribute("msg","余额不足，无法购买");
            return "redirect:/order/cart";
        }
        int i=orderService.payOrder(userId);
        //修改信用币
        Reader reader = readerService.getById(userId);
        reader.setMoney(reader.getMoney()-a);
        boolean b = readerService.updateById(reader);
        return "redirect:/order/myOrders";
    }


    //确认收货
    @RequestMapping("confirmOrder/{orderId}")
    public String confirmOrder(@PathVariable Integer orderId){
        Order order = orderService.getById(orderId);
        order.setStatus(2);
        orderService.updateById(order);
        //根据发布者获取读者
        Integer total = order.getTotal();
        Integer count = order.getCount();
        String sharer = bookService.getById(order.getBid()).getSharer();
        QueryWrapper<Reader>qw=new QueryWrapper<>();
        qw.eq("rname",sharer);
        Reader reader = readerService.getOne(qw);
        //发布者的信用币增加
        reader.setMoney(reader.getMoney()+total+10*count);//系统多奖励10个信用币。可自定义大小
        readerService.updateById(reader);
        return "redirect:/order/myOrders";
    }

    //删除我的订单
    @RequestMapping("delMyOrder/{id}")
    public String delMyOrder(@PathVariable Integer id){
        boolean b = orderService.removeById(id);
        return "redirect:/order/myOrders";
    }

    //批量删除我的订单
    @PostMapping("batchDeleteMyOrder")
    @ResponseBody
    public String batchDeleteReaderBook(String idList){
        String[]split= StrUtil.split(idList,",");
        List<Integer> list=new ArrayList<>();

        for (String s : split) {
            if (!s.isEmpty()){
                int i = Integer.parseInt(s);
                list.add(i);
            }
        }
        boolean b = orderService.removeByIds(list);
        if (b){
            return "OK";
        }else {
            return "error";
        }
    }

    //批量删除我的出售
    @PostMapping("batchDeleteMySale")
    @ResponseBody
    public String batchDeleteMySale(String idList){
        String[]split= StrUtil.split(idList,",");
        List<Integer> list=new ArrayList<>();

        for (String s : split) {
            if (!s.isEmpty()){
                int i = Integer.parseInt(s);
                list.add(i);
            }
        }
        boolean b = orderService.removeByIds(list);
        if (b){
            return "OK";
        }else {
            return "error";
        }
    }


    //跳转到修改我的订单页面
    @RequestMapping("preUpdateMyOrder/{id}")
    public String preUpdateMyOrder(@PathVariable Integer id,Model model){
        Order order = orderService.getById(id);
        Integer rid = order.getRid();
        Integer bid = order.getBid();
        Reader reader = readerService.getById(rid);
        Book book = bookService.getById(bid);
        model.addAttribute("book",book);
        model.addAttribute("reader",reader);
        model.addAttribute("order",order);
        return "myOrders-update";
    }

    //修改我的订单
    @RequestMapping("updateMyOrder")
    public String updateMyOrder(Integer id,Integer count){
        Order order = orderService.getById(id);
        Integer oldCount = order.getCount();
        Integer bid = order.getBid();
        Book book = bookService.getById(bid);
        order.setCount(count);
        order.setTotal(count* book.getPrice());
        orderService.updateById(order);
        //修改库存
        if (oldCount>count){
            //库存加
            book.setStock(book.getStock()+(oldCount-count));
            bookService.updateById(book);
        }else {
            //库存减
            book.setStock(book.getStock()-(count-oldCount));
            bookService.updateById(book);
        }
        return "redirect:/order/myOrders";
    }


    //我的出售
    @RequestMapping("mySale")
    public String mySale(@RequestParam(required = false,defaultValue = "1",value = "pageNum") Integer pageNum,
                         @RequestParam(required = false,defaultValue = "10",value = "pageSize") Integer pageSize, Model model, Book book, HttpSession session){
        if (pageNum <= 0 || pageNum.equals("") || pageNum == null) {
            pageNum = 1;
        }
        if (pageSize <= 0 || pageSize.equals("") || pageSize == null) {
            pageSize = 10;
        }
        String userName =(String) session.getAttribute("currentUser");
        PageHelper.startPage(pageNum, pageSize);
        String bookName = book.getBname();
        PageInfo<Order> pageInfo=orderService.listMySale(userName,bookName);
        model.addAttribute("pageInfo",pageInfo);
        return "mySale-list";
    }


    //发货
    @RequestMapping("sendMessage/{email}/{bname}/{orderId}")
    public String sendMessage(@PathVariable String email,@PathVariable String bname,@PathVariable Integer orderId){
        log.info(email);
        log.info(bname);
        MailUtils.sendMail(email,"您订购的"+bname+"教材正在派送中，请注意查收","发货邮件");
        Order byId = orderService.getById(orderId);
        byId.setStatus(1);
        orderService.updateById(byId);
        return "redirect:/order/mySale";
    }

    //申请售后
    @RequestMapping("shouhou/{id}")
    public String shouhou(@PathVariable Integer id){
        Order byId = orderService.getById(id);
        byId.setShouhou(1);
        boolean b = orderService.updateById(byId);
        return "redirect:/order/myOrders";
    }

    //处理售后
    @RequestMapping("handle/{id}")
    public String handle(@PathVariable Integer id){
        Order byId = orderService.getById(id);
        byId.setShouhou(2);
        boolean b = orderService.updateById(byId);
        return "redirect:/order/listOrder";
    }

}
